<template>
  <div class="detail">
    <!-- 主图轮播 -->
    <van-swipe :autoplay="3000" lazy-render>
      <van-swipe-item v-for="image in banners" :key="image">
        <img :src="image" />
      </van-swipe-item>
    </van-swipe>

    <!-- 商品价格及规格 -->
    <div class="title">{{ detail?.proname }}</div>
    <div class="desc">{{ detail?.desc }}</div>
    <div class="price">原价：{{ detail?.originprice }}</div>
    <!-- 商品详情 -->

    <!-- 详情页面动作栏 -->
    <van-action-bar>
      <van-action-bar-icon icon="chat-o" text="客服" dot />
      <van-action-bar-icon icon="cart-o" text="购物车" :badge="store.totaAmount" to="/cart"/>
      <van-action-bar-icon icon="star-o" text="收藏" />
      <van-action-bar-button type="warning" text="加入购物车" @click="handleAddToCart"/>
      <van-action-bar-button type="danger" text="立即购买" /> 
    </van-action-bar>

  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue"
import { useRoute } from "vue-router"
import { showSuccessToast } from "vant";
import { getDetail } from "@/api/detail"
import useCartStore from "@/store/modules/cart";


//获取当前激活路由的配置对象 
const route = useRoute()


//根据参数中的商品编号查询商品详情数据 

//详情数据
const detail = ref<Product>()
//主图轮播
const banners = computed(() => {  
  if (detail.value) {
    return [
      detail.value.img1,
      detail.value.img2,
      detail.value.img3,
      detail.value.img4,

    ]
  }
  return [] 
})
const fetchDetail = async () => {
  try {
    const result = await getDetail(route.query.proid as string)
    console.log("result", result)
    detail.value = result
  } catch (error) {
    console.error("异常", error)
  }
}
fetchDetail()

// 加入购物车

const store = useCartStore() //调用 useCartStore（）函数，获取购物车相关的store
 
const handleAddToCart = () =>{
  // console.log("in...")
  if(!detail.value){
    return
  }
  //从商品详情中解构需要使用到的数据
  const {proid ,proname,originprice,discount,img1}= detail.value
  //从当前选购的商品对象
  const currentProd:CartProduct = {
    id:proid, 
    title:proname,
    price:Number((originprice * discount /10).toFixed(2)),
    thumb:img1
  }
  //从当前选购商品保存到购物车数组中（修改store 中的 state数据）
  store.addToCart(currentProd)
  //提示
  showSuccessToast("加入成功")
}
</script>
 
<style lang="less" scoped></style>
